﻿
Imports std

Public Module logmerger

    Public Const defaultConfigfile As String = "logmerger.ini"
    Private WithEvents config As configMonitor = Nothing
    Private processors As vector(Of processor) = Nothing

    Public Sub startservice()
        assert(Not config Is Nothing, "should set config before start service.")
        Dim str As String = Nothing
        Dim procs As vector(Of String) = Nothing
        str = config.parameter(configNaming.logmerger.name, configNaming.logmerger.processors _
                               , configNaming.defaultValue.logmerger.processors)
        strsepar(str, character.comma, procs, character.quoteMark, True)
        processors = New vector(Of processor)
        Dim i As Int64
        For i = 0 To procs.size() - 1
            processors.push_back(New processor())
            processors(processors.size() - 1).initial(procs(i), config)
            processors(processors.size() - 1).start()
        Next
    End Sub

    Public Sub shutdown()
        If Not processors Is Nothing Then
            Dim i As Int64
            For i = 0 To processors.size() - 1
                processors(i).stop()
            Next
        End If
    End Sub

    Public Sub unhandledException(ByVal ex As Exception)
        shutdown()
    End Sub

    Public Sub main(ByVal args() As String)
        startmain(AddressOf unhandledException)

        Dim configfile As String = defaultConfigfile
        If args.Length() > 0 Then
            configfile = args(0)
        End If
        config = New configMonitor()
        assert(config.open(configfile), "cannot open configfile " + configfile)

        startservice()

        While Not consoleExtSignal()
            sleep()
        End While

        raiseError("caught console cancel key event, shutdown ...")
        shutdown()
        finishmain()
        forceQuit(0)
    End Sub

    Private Sub config_ConfigChanged() Handles config.ConfigChanged
        shutdown()
        startservice()
    End Sub

    Private Sub config_ConfigfileDeleted() Handles config.ConfigfileDeleted
        If configMonitor.defaultConfigDeletedOperation(60 * 60 * 1000, 60 * 60) Then
            shutdown()
        End If
    End Sub
End Module
